﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class DALBatteryItem : IDALBatteryItem, IDisposable
    {
        private CarBatteryEntities context;
        private bool disposed = false;

        public DALBatteryItem(CarBatteryEntities context)
        {
            this.context = context;
        }

        public BatteryItem FindBatteryItem(int ID)
        {
            return context.BatteryItem.FirstOrDefault(x => x.batteryID.Equals(ID));
        }

        public IEnumerable<BatteryItem> FindBatteryItemsAtLocation(string location)
        {
            return context.BatteryStation.Include(e => e.BatteryItem).Where(x => x.name.Equals(location)).SelectMany(x => x.BatteryItem).AsEnumerable();
        }

        public IEnumerable<BatteryItem> FindBatteryItemsAtLocationState(string location, double capacity, BatteryState state)
        {
            String batteryState = state.ToString();

            return context.BatteryStation.Include(e => e.BatteryItem).Where(x => x.name.Equals(location)).SelectMany(x => x.BatteryItem).Include(y => y.BatteryModel).Where(x => x.state.Equals(batteryState) && x.BatteryModel.capacity.Equals(capacity)).AsEnumerable();
        }

        public IEnumerable<BatteryItem> GetAllItems()
        {
            return context.BatteryItem.AsEnumerable();
        }

        public void InsertBatteryItem(BatteryItem batItem)
        {
            context.BatteryItem.Add(batItem);
        }

        public void DeleteBatteryItem(int batItemID)
        {
            context.BatteryItem.Remove(FindBatteryItem(batItemID));
        }

        public void UpdateBatteryItem(BatteryItem batItem)
        {
            context.Entry(batItem).State = EntityState.Modified;
        }

        public void UpdateBatteryState(BatteryItem batItem, BatteryState state)
        {
            batItem.state = state.ToString();
        }

        public int Save()
        {
            return context.SaveChanges();
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                    context.Dispose();
            }

            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}